from flask import Flask, jsonify, request
from flask_admin import Admin,AdminIndexView
from flask_admin.base import expose
from flask_ckeditor import CKEditor, CKEditorField
from os import path
import os
from models import db, HouseCompensation, NewsPolicy
from modelview import ArticleAdmin,MyHouseView
app = Flask(__name__)
BASEDIR = path.abspath(path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:Dbbc888#@sh-cynosdbmysql-grp-9cp5klow.sql.tencentcdb.com:26759/flask_demo'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['CKEDITOR_PKG_TYPE'] = 'full' # ckeditor的按钮种类分为basic，standard还有full
app.config['CKEDITOR_FILE_UPLOADER'] = 'upload' # 图片文件要上传路径
app.config['UPLOADED_PATH'] = path.join(BASEDIR,'files') # 图片上传文件夹

app.secret_key = 'fa2abGLSBA2lsn251l1051kb129161042'


# ckeditor = CKEditor(app=app)

db.init_app(app)

class MyAdminIndexView(AdminIndexView):
    is_visible = False
    
    def index(self):
        return super(MyAdminIndexView, self).index()

admin = Admin(app, name='补偿计算系统', template_mode='bootstrap3')

    

admin.add_view(ArticleAdmin(NewsPolicy, db.session, name=u'政策新闻'))
admin.add_view(MyHouseView(HouseCompensation, db.session,name='房屋补偿'))


def create_tables():
    """同步创建所有数据库表"""
    with app.app_context():
        db.create_all()
    return "所有表已成功创建"

@app.route('/api/news/list')
def get_news():
    news = NewsPolicy.query.all()
    news = NewsPolicy.query.with_entities(
        NewsPolicy.id,
        NewsPolicy.title,
        NewsPolicy.publish_date
    ).all()
    return jsonify([{
        'id':n.id,
        'title': n.title,
        'publish_date': n.publish_date.isoformat() if n.publish_date else None
    } for n in news])

@app.route('/api/news/<int:id>')
def get_news_detail(id):
    news = NewsPolicy.query.get_or_404(id)
    return jsonify({
        'id': news.id,
        'title': news.title,
        'content': news.content,
        'publish_date': news.publish_date.isoformat() if news.publish_date else None
    })


@app.route('/api/house', methods=['POST'])
def submit_house():
    data = request.json
    compensation = HouseCompensation(
        below300=data.get('below300', 0),
        above300=data.get('above300', 0),
        above0to100=data.get('above0to100', 0),
        above100to200=data.get('above100to200', 0),
        above200to300=data.get('above200to300', 0),
        brick=data.get('brick', 0),
        simple=data.get('simple', 0),
        shed=data.get('shed', 0),
        other=data.get('other', 0),
        decoration=data.get('decoration', 0),
        move=data.get('move', 0),
        facility=data.get('facility', 0),
        temporary=data.get('temporary', 0),
        signing=data.get('signing', 0),
        business1=data.get('business1', 0),
        business2=data.get('business2', 0),
        total=sum([
            data.get('below300', 0),
            data.get('above300', 0),
            data.get('above0to100', 0),
            data.get('above100to200', 0),
            data.get('above200to300', 0),
            data.get('brick', 0),
            data.get('simple', 0),
            data.get('shed', 0),
            data.get('other', 0),
            data.get('decoration', 0),
            data.get('move', 0),
            data.get('facility', 0),
            data.get('temporary', 0),
            data.get('signing', 0),
            data.get('business1', 0),
            data.get('business2', 0)
        ])
    )
    db.session.add(compensation)
    db.session.commit()
    return jsonify({'status': 'success', 'id': compensation.id})

if __name__ == '__main__':
    # 在启动应用时自动创建表
    # create_tables()
    
    app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 5000)))